package com.maopuyu.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class RequestUtils {
    public static Headers setHeaders(Map<String, String> headersParams) {
        okhttp3.Headers.Builder headersbuilder = new okhttp3.Headers.Builder();
        String[] keys = headersParams.keySet().toArray(new String[0]);
        for (String key : keys) {
            String value = headersParams.get(key);
            headersbuilder.add(key, value);
        }
        return headersbuilder.build();
    }

    public static String sendWXRequest(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            return "-1";
        }
    }

    public static String sendRequest(String url, Map<String, String> headersParams) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Headers setHeaders = setHeaders(headersParams);
        Request request = new Request.Builder().headers(setHeaders).url(url).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).string();
        } catch (IOException e) {
            return "-1";
        }
    }


    public static byte[] sendByteRequest(String uri) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(uri).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            return Objects.requireNonNull(response.body()).bytes();
        } catch (IOException e) {
            return "-1".getBytes();
        }
    }
}
